<template>
    <div class="wh-100 d-flex">
        <div :class="showRight ? 'w-80' : 'w-100'" class="h-100 card" style="background-color: white">
            <div class="mt-8 mb-8  d-flex-between-center">
                <div class=" h-100 d-flex-align-center">
                    <!--                <Button v-has="'add'" @click="add" type="primary" icon="md-add">添加</Button>-->
                    <Button v-has="'delete'" @click="delAll" icon="md-trash">批量删除</Button>
                    <Button @click="getDataList" icon="md-refresh">刷新</Button>
                    <!--              <Button v-has="'input'" @click="dropImportData">导入数据</Button>-->
                    <!--            <Button type="dashed" @click="openSearch=!openSearch">{{ openSearch ? "关闭搜索" : "开启搜索" }}</Button>-->
                    <Button type="dashed" @click="openTip=!openTip">{{ openTip ? '关闭提示' : '开启提示' }}</Button>
                    <Button type="primary" @click="batchBackArchive">批量转回档案信息</Button>
                    <Button v-if="resource !== '3'" type="primary" icon="ios-cloud-upload-outline"
                            @click="importFormView = true">导入档案信息
                    </Button>
                    <Modal
                        v-model="importFormView"
                        title="导入档案信息">
                        <Form :model="importForm" :label-width="80">
                            <div>注:导入档案信息时，请先导入生源信息，否则无法导入档案信息。</div>
                            <FormItem label="文件: ">
                                <Upload
                                    accept=".xls,.xlsx"
                                    :before-upload="handleUpload">
                                    <Button icon="ios-cloud-upload-outline">点击上传</Button>
                                </Upload>
                                <div v-if="importForm.file !== null">
                                    {{ importForm.file.name }}
                                </div>
                                <div>说明：请依据模板数据格式导入，文件格式必须为.xlsx</div>
                            </FormItem>
                        </Form>
                        <div slot="footer">
                            <Button @click="importFormcCncel">取消</Button>
                            <Button type="primary" :loading="importing" @click="importFormOk">开始上传</Button>
                        </div>
                    </Modal>
                    <Button @click="downloadTempleA" type="info">下载导入模板</Button>
                    <Button v-loading="exportingSelect" @click="dropExportSelect">导出所选数据</Button>
                    <Button v-loading="exportingAll" @click="dropExportAll">导出全部数据</Button>
                    <Button v-loading="exportingSearch" @click="dropExportSearch" class="mr-auto">下载当前查询数据
                    </Button>
                </div>
                <Button class="mr-8" :icon="showRight?`ios-arrow-forward`:`ios-arrow-back`"
                        @click.native="showRight =!showRight"
                        type="primary">
                </Button>
            </div>
            <div v-show="openTip">
                <Alert show-icon>
                    已选择 <span class="select-count">{{ selectList.length }}</span> 项
                    <a class="select-clear" @click="clearSelectAll">清空</a>
                </Alert>
            </div>
            <div v-ref-height="refHeight" class="h-80 w-100 calc-px-height">
                <!--                @on-row-dblclick="sjclaib"-->
                <Table :loading="loading"
                       border
                       :columns="columns"
                       :data="data"
                       ref="table"
                       sortable="custom"
                       no-data-text="暂无数据"
                       :height="refHeight.value"
                       @on-sort-change="changeSort"
                       @on-selection-change="changeSelect">
                    <template slot-scope="{ row, index }" slot="transferType">
                        <span v-if="row.transferType == 0">转回生源地</span>
                        <span v-else-if="row.transferType == 1">签约单位接收</span>
                        <span v-else-if="row.transferType == 2">托管单位接收</span>
                        <span v-else-if="row.transferType == 3">上级主管单位接收</span>
                        <span v-else-if="row.transferType == 4">升学本单位接收</span>
                        <span v-else-if="row.transferType == 5">升学外单位接收</span>
                        <span v-else-if="row.transferType == 9">暂不确定</span>
                    </template>
                    <template slot-scope="{ row, index }" slot="status">
                        <div class="wh-100">
                            <span v-if="row.status == 1">待填报</span>
                            <span v-if="row.status == 2">草稿</span>
                            <span v-if="row.status == 3">审核中</span>
                            <span v-if="row.status == 4">已撤回</span>
                            <span v-if="row.status == 5">已驳回</span>
                            <span v-if="row.status == 6">审核通过</span>
                        </div>
                    </template>
                </Table>
            </div>
            <div class="w-100 h-5 d-flex-around-center mt-12 ">
                <Page :current="searchForm.pageNumber"
                      :total="total"
                      :page-size="searchForm.pageSize"
                      @on-change="changePage"
                      @on-page-size-change="changePageSize"
                      :page-size-opts="[10,20,50,100,200]"
                      size="small" show-total
                      show-elevator
                      show-sizer>
                </Page>
            </div>
        </div>
        <div v-show="showRight" class="w_20-12 rightStyle h-100  ml-12 card">
            <div v-show="!modalVisible" @keydown.enter.native="handleSearch" class="wh-100 pl-8 pr-8">
                <div class=" pt-12 fs-16  fw-6 ">
                    查询区
                </div>
                <div><!--class="mt-52"-->
                    <Form ref="searchForm" :model="searchForm" :label-width="labelWidth" class="marginForm ">
                        <FormItem label="姓名" prop="xm" class=" w-95">
                            <Input type="text" v-model="searchForm.xm" placeholder="请输入姓名" clearable
                                   style="width: 100%" />
                        </FormItem>
                        <FormItem label="考生号" prop="ksh" class=" w-95">
                            <Input type="text" v-model="searchForm.ksh" placeholder="支持逗号间隔批量查询" clearable
                                   style="width: 100%" />
                        </FormItem>
                        <FormItem label="学号" prop="xh" class=" w-95">
                            <Input type="text" v-model="searchForm.xh" placeholder="支持逗号间隔批量查询" clearable
                                   style="width: 100%" />
                        </FormItem>
                        <FormItem label="身份证号" prop="sfzh" class=" w-95">
                            <Input type="text" v-model="searchForm.sfzh" placeholder="支持逗号间隔批量查询" clearable
                                   style="width: 100%" />
                        </FormItem>
                        <!--                        <FormItem v-if='resource === "1" || resource === "0"' label="院校代码" prop="schoolCode">-->
                        <!--                            <Input type="text" v-model="searchForm.schoolCode" placeholder="请输入院校代码" clearable style="width: 100%"/>-->
                        <!--                        </FormItem>-->
                        <FormItem label="专业" prop="zy" class=" w-95">
                            <Input type="text" v-model="searchForm.zy" placeholder="请输入专业名称" clearable
                                   style="width: 100%" />
                        </FormItem>
                        <FormItem v-if='resource === "1" || resource === "0"' label="学校" prop="schoolName"
                                  class=" w-95">
                            <Input type="text" v-model="searchForm.schoolName" placeholder="请输入院校名称" clearable
                                   style="width: 100%" />
                        </FormItem>
                        <FormItem label="院系" prop="college" class=" w-95">
                            <Input type="text" v-model="searchForm.college" placeholder="请输入学院名称" clearable
                                   style="width: 100%" />
                        </FormItem>
                        <FormItem label="学历" prop="college" class=" w-95">
                            <!--                            <Input type="text" v-model="searchForm.xlCode" placeholder="请输入学院名称" clearable style="width: 100%"/>-->
                            <Select v-model="searchForm.xlcc" clearable placeholder="请选择学历" class="w-100">
                                <Option v-for="(item,index) in xlList" :value="item.value" :key="index">{{ item.title
                                    }}
                                </Option>
                            </Select>
                        </FormItem>
                        <FormItem label="档案转递类型" prop="transferType" class=" w-95">
                            <Select v-model="searchForm.transferType" clearable placeholder="请选择档案转递类型"
                                    class="w-100">
                                <Option v-for="(item,index) in accountTypeList" :value="item.value" :key="index">
                                    {{ item.title }}
                                </Option>
                            </Select>
                        </FormItem>
                        <FormItem label="档案登记状态" prop="status" class=" w-95">
                            <Select v-model="searchForm.status" clearable placeholder="请选择档案登记状态"
                                    class="w-100">
                                <Option value="1">待填报</Option>
                                <Option value="2">草稿</Option>
                                <Option value="3">待学校审核</Option>
                                <Option value="20">待院系审核</Option>
                                <Option value="4">已撤回</Option>
                                <Option value="5">已驳回</Option>
                                <Option value="6">已登记</Option>
                            </Select>
                        </FormItem>
                        <FormItem label="毕业时间" prop="transferType" class=" w-95">
                            <DatePicker v-model="searchForm.bysj" clearable @on-change="dateChange" type="month"
                                        placeholder="毕业时间"></DatePicker>
                        </FormItem>
                        <FormItem label="生源所在地" prop="transferType" class=" w-95">
                            <el-cascader
                                clearable
                                class="w-100"
                                v-model="searchForm.unitLocation"
                                :options="locationOfTheUnitList"
                                :props="provincesAndMunicipalitiesProps"
                                @change="changeCar"
                            ></el-cascader>
                        </FormItem>
                        <FormItem label="数据来源" prop="importFlag" class="w-95">
                            <Select v-model="searchForm.importFlag" clearable placeholder="请选择数据来源"
                                    class="w-100">
                                <Option value="0">学生填报</Option>
                                <Option value="1">学校导入</Option>
                                <Option value="2">学院修改</Option>
                                <Option value="3">学校修改</Option>
                            </Select>
                        </FormItem>
                        <FormItem class="br box-key">
                            <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                            <Button @click="handleReset">重置</Button>
                        </FormItem>
                    </Form>
                </div>
            </div>
            <div v-show="modalVisible" class="wh-100 pl-8 pr-8">
                <div class=" pt-12 fs-16  fw-6 ">
                    {{ modalTitle }}
                </div>
                <div class="mt-52">
                    <Form ref="form" :model="form" :rules="formValidate" :label-width="90" label-position="left"
                          class="marginForm">
                        <p class="drawer-title">个人信息</p>
                        <FormItem label="姓名" prop="xm">
                            <Input v-model="form.xm" clearable maxlength="70" readonly />
                        </FormItem>
                        <FormItem label="考生号" prop="ksh">
                            <Input v-model="form.ksh" clearable maxlength="70" readonly />
                        </FormItem>
                        <FormItem label="学号" prop="xh">
                            <Input v-model="form.xh" clearable maxlength="70" readonly />
                        </FormItem>
                        <FormItem label="身份证号" prop="sfzh">
                            <Input v-model="form.sfzh" clearable maxlength="70" readonly />
                        </FormItem>
                        <FormItem label="院校名称" prop="schoolName">
                            <Input v-model="form.schoolName" clearable maxlength="70" readonly />
                        </FormItem>
                        <FormItem label="院系名称" prop="college">
                            <Input v-model="form.college" clearable maxlength="70" readonly />
                        </FormItem>

                        <!--              <FormItem label="学历层次" prop="xlccmc">-->
                        <!--                <Input v-model="form.xlccmc" clearable maxlength="70" readonly/>-->
                        <!--              </FormItem>-->
                        <Divider />
                        <p class="drawer-title">档案转递信息</p>
                        <FormItem
                            :rules="[{ required: true, message: '该项必填', trigger: 'change'}]"
                            prop="transferType"
                            label="转递类型">
                            <!--                <Select v-model="form.transferType" clearable>-->
                            <!--                  <Option value="0">请自行编辑下拉菜单</Option>-->
                            <!--                </Select>-->
                            <Select v-model="form.transferType" clearable placeholder="请选择档案转递类型"
                                    class="w-100">
                                <Option v-for="(item,index) in accountTypeList" :value="item.value" :key="index">
                                    {{ item.title }}
                                </Option>
                            </Select>
                        </FormItem>
                        <FormItem
                            :rules="[{ required: true, message: '该项必填', trigger: 'blur'}]"
                            prop="unitName"
                            label="转递单位名称">
                            <Input v-model="form.unitName" clearable />
                        </FormItem>
                        <FormItem
                            :rules="[{ required: true,  trigger: 'change',validator: validatelocationOfTheUnit}]"
                            label="转递单位所在地"
                            prop="unitLocation">
                            <el-cascader
                                clearable
                                class="w-100"
                                v-model="form.unitLocation"
                                :options="locationOfTheUnitList"
                                :props="provincesAndMunicipalitiesProps"
                                @change="changeUnitLocation"
                            ></el-cascader>
                        </FormItem>
                        <FormItem
                            prop="unitAddress"
                            :rules="[{ required: true, message: '该项必填', trigger: 'blur'}]">
                            <Input v-model="form.unitAddress" clearable placeholder="请填写档案转递单位详细地址" />
                        </FormItem>
                        <FormItem
                            :rules="[{ required: true, message: '该项必填', trigger: 'blur'},  { pattern: /^(0[1-7]|1[0-356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[0-5]|8[013-6])\d{4}$/, message: '请输入正确的邮政编码' }]"
                            prop="unitZip"
                            label="转递单位邮编">
                            <Input v-model="form.unitZip" clearable />
                        </FormItem>
                        <FormItem
                            :rules="[{ required: true, message: '该项必填', trigger: 'blur'}]"
                            prop="unitContact"
                            label="转递单位联系人">
                            <Input v-model="form.unitContact" clearable />
                        </FormItem>
                        <FormItem
                            :rules="[{ required: true, message: '该项必填', trigger: 'blur'},{
                                    pattern: /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/,
                                    message: '请输入正确的电话号码（如021-88888888）或手机号码'
                                }]"
                            prop="unitTel"
                            label="转递单位联系电话">
                            <Input v-model="form.unitTel" clearable />
                        </FormItem>
                        <FormItem
                            label="情况说明">
                            <Input v-model="form.unitRemark" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }"
                                   placeholder="选填(200字以内)"></Input>
                        </FormItem>
                        <FormItem
                            :rules="[{ required: true, trigger: 'blur' ,validator: validateEvidentiaryMaterial}]"
                            prop="imageMaterial"
                            label="上传证明材料">
                            <span
                                style="color:rgba(51, 51, 51, 0.4);">最多上传五张图片，相关户口迁移的证明材料供审核时参考</span>
                        </FormItem>
                        <FormItem>
                            <div class="">
                                <uploadPicture :images="backImages" @beforeUpload="beforeUpload"
                                               ref="supportingMaterialRef"
                                               :max-count="3"></uploadPicture>
                            </div>
                        </FormItem>
                        <FormItem>
                            <Button type="text" @click="modalVisible=false">取消</Button>
                            <div style="display: inline;">
                                <Button v-has="'edit'" type="primary" :loading="submitLoading" @click="handleSubmit">
                                    提交
                                </Button>
                            </div>
                        </FormItem>
                    </Form>
                </div>
            </div>

        </div>
    </div>
</template>

<script>
import excel from '@/libs/excel';
import {
    archiveTransferInfoColumns,
    archiveTransferInfoData
} from './importArchiveTransferInfoTemplate';
import {
    batchBackAPI,
    exportAllArchiveTransferInfo,
    exportSearchArchiveTransferInfo,
    exportSelectArchiveTransferInfo,
    getByLocationAPI,
    getByPageArchiveTransferInfo,
    importArchiveTransferInfoAPI,
    updateArchiveTransfer
} from '../../api/archivesManagement/archiveForwardingAddressApis';
import Cookies from 'js-cookie';
import { imageUploadDataApi, newProvincialDataApi } from '../../api/bys';
import { getDictDataByType } from '../../api';
import UploadPicture from '../../components/uploadPicture/uploadPicture.vue';
import { areaDataApi } from '../../api/common';

export default {
    name: 'archiveTransferInfo',
    components: { UploadPicture },
    data() {
        const validateEvidentiaryMaterial = (rule, value, callback) => {
            if (this.$refs.supportingMaterialRef.formFile.length > 0 || this.form.imageMaterial !== null) {
                callback();
            } else {
                callback(new Error('请上传证明材料'));
            }
        };
        const validatelocationOfTheUnit = (rule, value, callback) => {
            if (this.form.unitLocation === null || this.form.unitLocation === '') {
                callback(new Error('请选择档案转递所在地'));
            } else {
                callback();
            }
        };
        return {
            labelWidth: 100,
            validateEvidentiaryMaterial,
            validatelocationOfTheUnit,
            accountTypeList: [], // 档案转寄类型
            locationOfTheUnitList: [], // 单位所在地
            // 省市区级联
            provincesAndMunicipalitiesProps: {
                label: 'name',
                value: 'code',
                children: 'children'
            },
            resource: '',
            refHeight: { value: 0 },
            importing: false,
            exportingSearch: false,
            exportingSelect: false,
            exportingAll: false,
            importFormView: false,
            importForm: {
                file: null,
                importMode: '1'
            },
            openSearch: true, // 显示搜索
            openTip: true, // 显示提示
            loading: true, // 表单加载状态
            modalType: 0, // 添加或编辑标识
            modalVisible: false, // 添加或编辑显示
            modalTitle: '', // 添加或编辑标题
            height1: 0,
            searchForm: { // 搜索框初始化对象
                pageNumber: 1, // 当前页数
                pageSize: 50, // 页面大小
                sort: 'createTime', // 默认排序字段
                order: 'desc' // 默认排序方式
            },
            form: { // 添加或编辑表单对象初始化数据
                bysId: '',
                transferType: '',
                unitName: '',
                unitLocation: '',
                unitAddress: '',
                unitZip: '',
                unitContact: '',
                unitTel: '',
                isConfirm: ''
            },
            // 表单验证规则
            formValidate: {},
            submitLoading: false, // 添加或编辑提交状态
            selectList: [], // 多选数据
            columns: [],
            columns_1: [
                // 表头
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    type: 'index',
                    title: '序号',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '数据来源',
                    minWidth: 100,
                    key: 'importFlag', // 0是学生填报 1是学校导入 2是学院修改 3是学校修改
                    sortable: false,
                    render: (h, params) => {
                        if (params.row.importFlag == 0) {
                            return h('span', '学生填报');
                        } else if (params.row.importFlag == 1) {
                            return h('span', '学校导入');
                        } else if (params.row.importFlag == 2) {
                            return h('span', '学院修改');
                        } else if (params.row.importFlag == 3) {
                            return h('span', '学校修改');
                        }
                    }
                },
                {
                    title: '院校名称',
                    key: 'schoolName',
                    minWidth: 180,
                    sortable: false
                },
                {
                    title: '院系名称',
                    key: 'college',
                    minWidth: 140,
                    sortable: false
                },
                {
                    title: '专业',
                    key: 'zy',
                    minWidth: 140,
                    sortable: false
                },
                {
                    title: '姓名',
                    key: 'xm',
                    minWidth: 100,
                    sortable: false
                },
                {
                    title: '身份证号',
                    key: 'sfzh',
                    minWidth: 180,
                    sortable: false
                },
                {
                    title: '考生号',
                    key: 'ksh',
                    minWidth: 150,
                    sortable: false
                },
                {
                    title: '学号',
                    key: 'xh',
                    minWidth: 140,
                    sortable: false
                },
                {
                    title: '学历',
                    key: 'xlcc',
                    minWidth: 90,
                    sortable: false,
                    render: (h, params) => {
                        return h('span', this.xlList.find(item => item.value === params.row.xlcc).title);
                    }
                },
                {
                    title: '毕业时间',
                    key: 'bysj',
                    minWidth: 90,
                    sortable: false
                },
                {
                    title: '生源所在地',
                    key: 'sydCode',
                    minWidth: 200,
                    sortable: false,
                    render: (h, params) => {
                        return h('span', this.areaList.find(item => item.code == params.row.sydCode) ? this.areaList.find(item => item.code == params.row.sydCode).allName : '');
                    }
                },


                // {
                //   title: "学历层次",
                //   key: "xlccmc",
                //   minWidth: 120,
                //   sortable: false,
                // },
                {
                    title: '档案转递类型',
                    slot: 'transferType',
                    minWidth: 120,
                    sortable: false
                },
                {
                    title: '档案转递单位名称',
                    key: 'unitName',
                    minWidth: 200,
                    sortable: false
                },
                {
                    title: '档案转递单位所在地',
                    key: 'unitLocationName',
                    minWidth: 200,
                    sortable: false
                },
                {
                    title: '档案转递详细地址',
                    key: 'unitAddress',
                    minWidth: 300,
                    sortable: false
                },
                {
                    title: '档案转递单位邮编',
                    key: 'unitZip',
                    minWidth: 120,
                    sortable: false
                },
              {
                title: '档案转递单编号',
                key: 'emsOrder',
                minWidth: 150,
                sortable: false
              },
                {
                    title: '档案转递单位联系人',
                    key: 'unitContact',
                    minWidth: 200,
                    sortable: false
                },
                {
                    title: '档案转递单位联系电话',
                    key: 'unitTel',
                    minWidth: 180,
                    sortable: false
                },
                {
                    title: '更新时间',
                    key: 'updateTime',
                    minWidth: 180,
                    sortable: false
                },
                {
                    title: '档案登记状态',
                    slot: 'status',
                    align: 'center',
                    width: 120,
                    fixed: 'right'
                },

                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    width: 200,
                    fixed: 'right',
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'a',
                                {
                                    style: {
                                        display: this.hasPermission(this, 'edit') ? 'inline-block' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.edit(params.row);
                                        }
                                    }
                                },
                                '编辑'
                            ),
                            h('Divider', {
                                props: {
                                    type: 'vertical'
                                }
                            }),
                            h(
                                'a',
                                {
                                    style: {
                                        display: this.hasPermission(this, 'delete') ? 'inline-block' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.remove(params.row);
                                        }
                                    }
                                },
                                '删除'
                            ),
                            h('Divider', {
                                props: {
                                    type: 'vertical'
                                }
                            }),
                            h(
                                'a',
                                {
                                    style: {
                                        display: this.hasPermission(this, 'edit') ? 'inline-block' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.select(params.row);
                                        }
                                    }
                                },
                                '查看'
                            ),
                            h('Divider', {
                                props: {
                                    type: 'vertical'
                                }
                            }),
                            h(
                                'a',
                                {
                                    style: {
                                        display: this.hasPermission(this, 'edit') ? 'inline-block' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.reviewHistory(params.row);
                                        }
                                    }
                                },
                                '历史'
                            )
                        ]);
                    }
                }
            ],
            data: [], // 表单数据
            total: 0, // 表单数据总数
            importModalVisible: false,
            importTableData: [],
            importColumns: [],
            uploadfile: {
                name: ''
            },
            reading: false,
            importLoading: false,
            height: 510,
            tempColumns: archiveTransferInfoColumns,
            tempData: archiveTransferInfoData,
            showRight: true,
            xlList: [],
            backImages: '',
            areaList: []
        };
    },
    methods: {
        onRestWindow() {
            this.columns = this.restTableCellWidth(this.columns_1);
            this.labelWidth = this.searchLabelWidth(this.labelWidth);
        },
        reviewHistory(row) {
            this.$router.push({
                name: 'ArchiveReviewHistory',
                query: {
                    userId: row.userid
                }
            });
        },
        async getareaData() {
            let res = await areaDataApi();
            if (res.code === 200) {
                this.areaList = res.result;

                console.log('this.areaList', this.areaList.filter((item) => item.code == 411626));
            }
        },
        beforeUpload() {
            this.$refs.form.validateField('imageMaterial');

        },
        batchBackArchive() {
            let ids = this.selectList.map((item) => {return item.id;})
            batchBackAPI({
                ids: ids,
            }).then(res => {
                if (res.result) {
                    this.$message.success('批量转回生源地成功')
                }
                this.getDataList();
            }).catch(err => {
                this.$message.error('批量转回生源地失败');
            })

        },

        dropExportSearch() {
            this.exportingSearch = true;
            exportSearchArchiveTransferInfo(this.searchForm).then(res => {
                this.exportingSearch = false;
                const blob = new Blob([res], { type: 'charset=utf-8' });
                let url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.style.display = 'none';
                link.href = url;
                link.setAttribute('download', '档案信息.xlsx');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link); // 删除节点
                window.URL.revokeObjectURL(url); //释放该 url
            });
        },
        dropExportSelect() {
            let ids = [];
            this.selectList.forEach(function(e) {
                ids.push(e.id);
            });
            this.exportingSelect = true;
            exportSelectArchiveTransferInfo({ ids: ids }).then(res => {
                this.exportingSelect = false;
                // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
                const blob = new Blob([res], { type: 'charset=utf-8' });
                let url = window.URL.createObjectURL(blob);

                const link = document.createElement('a');
                link.style.display = 'none';
                link.href = url;
                link.setAttribute('download', '档案信息.xlsx');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link); // 删除节点
                window.URL.revokeObjectURL(url); //释放该 url
            });
            console.log(ids);
        },

        dropExportAll() {
            this.exportingAll = true;
            exportAllArchiveTransferInfo().then(res => {
                this.exportingAll = false;
                // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
                const blob = new Blob([res], { type: 'charset=utf-8' });
                let url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.style.display = 'none';
                link.href = url;
                link.setAttribute('download', '档案信息.xlsx');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link); // 删除节点
                window.URL.revokeObjectURL(url); //释放该 url
            });
        },

        obtainTheAccountMigrationType() {
            getDictDataByType('file-forwarding-type').then(res => {
                if (res.code === 200) {
                    this.accountTypeList = res.result;
                }
            });
        },
        newObtainTheCascadingDataOfProvincesAndCities() {
            newProvincialDataApi().then((res) => {
                this.locationOfTheUnitList = res.result;
                console.log('this.locationOfTheUnitList', this.locationOfTheUnitList);
            });
        },
        async getxlList() {
            let res = await getDictDataByType('eduLevelType');
            if (res.code === 200) {
                this.xlList = res.result;
            }
        },
        selectListMe() {
            this.newObtainTheCascadingDataOfProvincesAndCities();
            this.obtainTheAccountMigrationType();
        },
        dateChange(data) {
            this.searchForm.bysj = data.split('-')[0] + data.split('-')[1];
        },
        changeUnitLocation() {
            this.$refs.form.validateField('unitLocation');
            let whereAddressName = [];
            let LocationCode = this.form.unitLocation;
            for (let i = 0; i < this.locationOfTheUnitList.length; i++) {
                if (this.locationOfTheUnitList[i].code == LocationCode[0]) {
                    whereAddressName.push(this.locationOfTheUnitList[i].name);
                }
                if (this.locationOfTheUnitList[i].children) {
                    let children = this.locationOfTheUnitList[i].children;
                    for (let j = 0; j < children.length; j++) {
                        if (children[j].code == LocationCode[1]) {
                            whereAddressName.push(children[j].name);
                        }
                        if (children[j].children) {
                            let children2 = children[j].children;
                            for (let k = 0; k < children2.length; k++) {
                                if (children2[k].code == LocationCode[2]) {
                                    whereAddressName.push(children2[k].name);
                                }
                            }
                        }
                    }
                }
            }
            this.getByLocation(this.form.unitLocation[2], this.form.sfzh);
            this.form.unitLocationName = whereAddressName.toString();
        },
        getByLocation(locationCode, idCard) {
            getByLocationAPI({ locationCode: locationCode, idCard: idCard }).then((res) => {
                console.log('res', res);
                let result = res.result[0];
                // 非师范
                if (result.isNormal == 0) {
                    if (result.notNormalUnitName && result.notNormalUnitAddress.length > 1) {
                        let address = {
                            unitName: result.notNormalUnitName || '',
                            unitAddress: result.notNormalUnitAddress || '',
                            unitZip: result.notNormalUnitZip || '',
                            unitContact: result.notNormalUnitContact || '',
                            unitTel: result.notNormalUnitTel || ''
                        };
                        this.$Modal.confirm({
                            title: '系统档案转递地址',
                            content: '检测到系统中当前填写的转递所在地有转递信息，是否使用系统信息覆盖当前填写信息？',
                            onOk: () => {
                                this.form.unitName = address.unitName;
                                this.form.unitAddress = address.unitAddress;
                                this.form.unitZip = address.unitZip;
                                this.form.unitContact = address.unitContact;
                                this.form.unitTel = address.unitTel;
                            },
                            onCancel: () => {
                            }
                        });
                        // this.replaceTheForwardingInformation(address)
                    }
                } else {
                    //   师范
                    if (result.normalUnitName && result.normalUnitAddress.length > 1) {
                        let address = {
                            unitName: result.normalUnitName || '',
                            unitAddress: result.normalUnitAddress || '',
                            unitZip: result.normalUnitZip || '',
                            unitContact: result.normalUnitContact || '',
                            unitTel: result.normalUnitTel || ''
                        };
                        this.$Modal.confirm({
                            title: '系统档案转递地址',
                            content: '检测到系统中当前填写的转递所在地有转递信息，是否使用系统信息覆盖当前填写信息？',
                            onOk: () => {
                                this.form.unitName = address.unitName;
                                this.form.unitAddress = address.unitAddress;
                                this.form.unitZip = address.unitZip;
                                this.form.unitContact = address.unitContact;
                                this.form.unitTel = address.unitTel;
                            },
                            onCancel: () => {
                            }
                        });
                        // this.replaceTheForwardingInformation(address)
                    }
                }
            });
        },
        changeCar() {
            this.searchForm.sydCode = this.searchForm.unitLocation[2];
        },
        // region TODO 导入档案信息 下载导入模板
        handleUpload(file) {
            const fileExt = file.name.split('.').pop().toLocaleLowerCase();
            if (!(fileExt == 'xlsx' || fileExt == 'xls')) {
                this.$Notice.warning({
                    title: '文件类型错误',
                    desc:
                        '所选文件‘ ' +
                        file.name +
                        ' ’不是EXCEL文件，请选择后缀为.xlsx或者.xls的文件。'
                });
            } else {
                this.importForm.file = file;
            }
            // this.importForm.file = file;
            return false;
        },
        downloadTempleA() {
            window.location.href = process.env.BASE_URL + '档案信息导入模板.xlsx';
        },
        async importFormOk() {
            if (this.importForm.file == null) {
                this.$Message.info('请选择文件');
                return;
            }
            let formData = new FormData();
            // formData.append('importMode', this.importForm.importMode); // 添加参数
            formData.append('file', this.importForm.file);
            this.importing = true;
            importArchiveTransferInfoAPI(formData).then(res => {
                this.$Message.success(res.result.result);
                if (res.result.importErrorVoList && res.result.importErrorVoList.length > 0) {
                    const data = res.result.importErrorVoList;
                    // 创建一个工作簿
                    const dataNew = [
                        ['数据', '原因', '行号']
                    ];

                    for (let i = 0; i < data.length; i++) {
                        let rowData = [
                            data[i].data,
                            data[i].reason,
                            data[i].row
                        ];
                        dataNew.push(rowData);
                    }
                    const ws = XLSX.utils.aoa_to_sheet(dataNew);
                    const wb = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

                    // 生成 Excel 文件并触发下载
                    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
                    const blob = new Blob([wbout], { type: 'application/octet-stream' });
                    const url = URL.createObjectURL(blob);

                    const a = document.createElement('a');
                    a.href = url;
                    a.download = '导入失败数据汇总.xlsx';
                    a.click();

                    // 清理
                    URL.revokeObjectURL(url);


                }
                // this.submitLoading = false;
                this.importing = false;
                this.importFormcCncel();
                this.getDataList();
            });
        },
        importFormcCncel() {
            this.importForm.file = null;
            this.importFormView = false;
        },
        // endregion
        async init() {
            await this.getareaData();
            await this.getxlList();
            this.getDataList();
            this.selectListMe();
        },
        // 显示隐藏右侧区域
        clickShowRight() {
            this.showRight = !this.showRight;
        },
        clearImportData() {
            this.importTableData = [];
            this.importColumns = [];
            this.uploadfile = {};
        },
        dropImportData() {
            this.importModalVisible = true;
        },
        downloadTemple() {
            let title = [];
            let key = [];
            archiveTransferInfoColumns.forEach((e) => {
                title.push(e.title);
                key.push(e.key);
            });
            const params = {
                title: title,
                key: key,
                data: archiveTransferInfoData,
                autoWidth: true,
                filename: '导入档案转递信息数据模版'
            };
            excel.export_array_to_excel(params);
            // window.location.href = process.env.BASE_URL + "字典导入模板.xlsx";
        },
        beforeUploadImport(file) {
            this.uploadfile = file;
            const fileExt = file.name.split('.').pop().toLocaleLowerCase();
            if (fileExt == 'xlsx' || fileExt == 'xls') {
                this.readFile(file);
                this.file = file;
            } else {
                this.$Notice.warning({
                    title: '文件类型错误',
                    desc:
                        '所选文件‘ ' +
                        file.name +
                        ' ’不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
                });
            }
            return false;
        },
        // 读取文件
        readFile(file) {
            this.reading = true;
            const reader = new FileReader();
            reader.readAsArrayBuffer(file);
            reader.onerror = (e) => {
                this.reading = false;
                // this.$Message.error("文件读取出错");
                this.$Message.error({
                    content: '文件读取出错',
                    duration: 5,
                    closable: true
                });
            };
            reader.onload = (e) => {
                const data = e.target.result;
                const { header, results } = excel.read(data, 'array');
                const tableTitle = header.map((item) => {
                    return { title: item, key: item, minWidth: 130, align: 'center' };
                });
                this.importTableData = results;
                this.importColumns = tableTitle;
                this.reading = false;
                this.$Message.success('读取数据成功');
            };
        },
        importData() {
            let params = this.importTableData.map(item => {
                return {
                    bysIdCard: item['毕业生身份证号'],
                    transferType: item['转递类型'],
                    unitName: item['转递单位名称'],
                    unitLocation: item['转递单位所在地'],
                    unitAddress: item['转递详细地址'],
                    unitZip: item['转递单位邮编'],
                    unitContact: item['转递单位联系人'],
                    unitTel: item['转递单位联系电话']
                };
            });
            this.importLoading = true;
            // importArchiveTransferInfoData(params).then((res) => {
            //   this.importLoading = false;
            //   if (res.success) {
            //     this.importModalVisible = false;
            //     this.getDataList();
            //     this.$Modal.info({
            //       title: "导入结果",
            //       content: res.message,
            //     });
            //   }
            // });
        },
        changePage(v) {
            this.searchForm.pageNumber = v;
            this.getDataList();
            this.clearSelectAll();
        },
        changePageSize(v) {
            this.searchForm.pageSize = v;
            this.getDataList();
        },
        handleSearch() {
            this.searchForm.pageNumber = 1;
            this.searchForm.pageSize = 50;
            this.getDataList();
        },
        handleReset() {
            this.$refs.searchForm.resetFields();
            this.searchForm.xm = null;
            this.searchForm.sfzh = null;
            this.searchForm.ksh = null;
            this.searchForm.bysj = null;
            this.searchForm.xh = null;
            this.searchForm.zy = null;
            this.searchForm.schoolName = null;
            this.searchForm.college = null;
            this.searchForm.xlcc = null;
            this.searchForm.transferType = null;
            this.searchForm.status = null;
            this.searchForm.unitLocation = null;
            this.searchForm.sydCode = null;
            this.searchForm.pageNumber = 1;
            this.searchForm.pageSize = 50;
            // 重新加载数据
            this.getDataList();
        },
        changeSort(e) {
            this.searchForm.sort = e.key;
            this.searchForm.order = e.order;
            if (e.order === 'normal') {
                this.searchForm.order = '';
            }
            this.getDataList();
        },
        clearSelectAll() {
            this.$refs.table.selectAll(false);
        },
        changeSelect(e) {
            this.selectList = e;

        },
        tableheig() {
            // var bbb = document.getElementsByClassName('calc-px-height')[0].scrollHeight;
            // var aaa = document.getElementsByClassName('calc-px-height')[0].children[0].children[0].children[1];
            // var ccc = document.getElementsByClassName('calc-px-height')[0].children[0].children[0].children[0].scrollHeight;
            // var ddd = bbb - ccc;
            // console.log(bbb, '00000000000000');
            // aaa.style.height = `${ddd - 4}px`;
        },

        getDataList() {
            this.loading = true;
            // 带多条件搜索参数获取表单数据 请自行修改接口
            getByPageArchiveTransferInfo(this.searchForm).then(res => {
                if (res.success) {
                    let value = res.result;
                    this.data = value.list;
                    this.total = value.pageination.total;
                    console.log('this.data', this.data);
                    this.tableheig();
                    this.loading = false;

                } else {
                    this.loading = false;
                }
            });
        },
        handleSubmit() {
            this.$refs.form.validate(async valid => {
                if (valid) {
                    this.submitLoading = true;


                    let zmcl = [];
                    for (let i = 0; i < this.$refs.supportingMaterialRef.formFile.length; i++) {
                        let file = this.$refs.supportingMaterialRef.formFile[i];
                        if (file.type) {
                            // region TODO 上传证明材料
                            const formData = new FormData();
                            formData.append('file', file);
                            const uploadResponse = await imageUploadDataApi(formData);
                            if (uploadResponse.code == 200) {
                                this.$refs.supportingMaterialRef.formFile[i] = uploadResponse.result;
                            }
                        }
                    }
                    zmcl = this.$refs.supportingMaterialRef.formFile;
                    this.form.imageMaterial = zmcl;


                    // 编辑
                    updateArchiveTransfer(this.form).then(res => {
                        this.submitLoading = false;
                        if (res.success) {
                            this.$Message.success('操作成功');
                            this.getDataList();
                            this.modalVisible = false;
                        }
                        if (res.code == 700) {
                            this.$Message.error(res.message);
                        }
                    });
                    // 模拟请求成功
                    // this.submitLoading = false;
                    // this.$Message.success("操作成功");
                    // this.getDataList();
                    // this.modalVisible = false;

                }
            });
        },
        add() {
            this.modalType = 0;
            this.modalTitle = '添加';
            this.$refs.form.resetFields();
            delete this.form.id;
            this.modalVisible = true;
        },
        sjclaib(v) {
            this.showRight = true;
            this.modalType = 1;
            this.modalTitle = '编辑区';
            this.$refs.form.resetFields();
            // 转换null为""
            for (let attr in v) {
                if (v[attr] === null) {
                    v[attr] = '';
                }
            }
            let str = JSON.stringify(v);
            let data = JSON.parse(str);
            this.form = data;
            this.modalVisible = true;
        },
        edit(v) {
            console.log('this.form', v);
            this.$router.push({ name: 'ArchiveTransferInfoEdit', params: { row: v } });
        },
        remove(v) {
            let param = {
                ids: v.id
            };
            this.$Modal.confirm({
                title: '确认删除',
                // 记得确认修改此处
                render: (h) => {
                    return h('div', [
                        h('p', '您确认要删除该条数据吗?（' + v.xm + ',身份证号:' + v.sfzh + '）'),
                        h('p', { style: '' }, '注:删除即清空该学生的档案相关信息，基本信息不删除！')
                    ]);
                },
                loading: true,
                onOk: () => {

                    if (v.status == 1 || v.status == 6) {
                        this.postRequest('/archiveTransferInfo/delByIds', param).then(res => {
                            this.$Modal.remove();
                            if (res.success) {
                                this.$Message.success('操作成功');
                                this.clearSelectAll();
                                this.getDataList();
                            }
                        });
                    } else {
                        this.$Message.error('审核中的数据无法删除！');
                        this.$Modal.remove();
                        this.clearSelectAll();
                        this.getDataList();
                    }


                    // 删除

                    // 模拟请求成功
                    // this.$Message.success("操作成功");
                    // this.clearSelectAll();
                    // this.$Modal.remove();
                    // this.getDataList();
                }
            });
        },
        select(row) {
            this.$router.push({ name: 'ArchiveTransferSelect', params: { row: row } });
        },
        delAll() {
            if (this.selectList.length <= 0) {
                this.$Message.warning('您还未选择要删除的数据');
                return;
            }
            this.$Modal.confirm({
                title: '确认删除',
                render: (h) => {
                    return h('div', [
                        h('p', '您确认要删除所选的 ' + this.selectList.length + ' 条数据?'),
                        h('p', { style: '' }, '注:删除即清空该学生的档案相关信息，基本信息不删除；审核中的数据也无法删除，系统会跳过审核中的数据！')
                    ]);
                },
                loading: true,
                onOk: () => {
                    let ids = '';
                    this.selectList.forEach(function(e) {
                        ids += e.id + ',';
                    });
                    ids = ids.substring(0, ids.length - 1);
                    // 批量删除
                    this.postRequest('/archiveTransferInfo/delByIds/', { ids: ids }).then(res => {
                        this.$Modal.remove();
                        if (res.success) {
                            this.$Message.success('操作成功');
                            this.clearSelectAll();
                            this.getDataList();
                        }
                    });
                    // 模拟请求成功
                    // this.$Message.success("操作成功");
                    // this.$Modal.remove();
                    // this.clearSelectAll();
                    // this.getDataList();
                }
            });
        }
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.onRestWindow);
    },
    created() {
        this.onRestWindow();
        window.addEventListener('resize', this.onRestWindow);
        // eduLevelType 学历层次


        this.resource = JSON.parse(Cookies.get('userInfo')).resource;
        this.init();
    }
};
</script>
<style lang="less" scoped>

//form表单间距统一修改
.ivu-form-item {
    margin-bottom: 0.01rem !important;
}

.card {
    background: white;
    transition: box-shadow .3s ease, transform .2s ease;
}

.card:hover {
    box-shadow: 0 4px 8px #23232333;
}

.w_20-12 {
    width: calc(20% - 12px);
}


@media (max-width: 1920px) {

    /deep/ .ivu-table .ivu-table-fixed-right {
        height: 98% !important;
    }

    /deep/ .ivu-table .ivu-table-fixed-right .ivu-table-fixed-body {
        height: 94% !important;
    }

    /deep/ .ivu-table-body {
        height: 94% !important;
    }
}

// 重构样式
/deep/ .ivu-form-item-label {
    display: flex;
    justify-content: right;
    width: 150px !important;
}

/deep/ .ivu-form-item {
    width: 100%;
    margin-bottom: 0.1rem;
    margin-right: 0 !important;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

/deep/ .ivu-form-item-content {
    width: 100% !important;
    margin-left: 0 ! important;
}

/deep/ .ivu-select {
    width: 100% !important;
}

/deep/ .ivu-date-picker {
    width: 100% !important;
}

/deep/ .br {
    margin-top: 15px;
    bottom: 0.12rem !important;

    .ivu-form-item-content {
        display: flex;
    }
}

/deep/ .ivu-input-type-textarea, /deep/ .ivu-input {
    height: calc(100% - 7px) !important;
}

.flex-1 {
    height: 100%;
}

/deep/ .ivu-drawer-body {
    overflow: hidden;

    .d-flex-align-center {
        height: fit-content !important;
        margin-left: 0 !important;
        justify-content: right;
        box-sizing: border-box;
        padding-right: 7px;
    }
}

.box-key {
    /deep/ .ivu-form-item-content {
        margin-left: 95px !important;
    }
}
</style>
